﻿using UnityEngine;
using LitJson;
using System.IO;
using System.Collections;


public class StartCommand : MonoBehaviour 
{
	public Animator move;
	void Start () 
	{
		InitShelf ();
	}

	/// <summary>
	/// 初始化书架
	/// </summary>
	public void InitShelf()
	{
		LoadBookList ();
	}
	/// <summary>
	/// 加载书架列表
	/// </summary>
	private void LoadBookList()
	{
		string jPath = Application.streamingAssetsPath + "/BookShelfList.json";
		if (!File.Exists(jPath))
			return;
		string json = File.ReadAllText(jPath);
		JsonData jd = JsonMapper.ToObject (json);
		JsonData jdItems = jd ["details"];
		for(int i=0;i<jdItems.Count;i++)
		{
			//Debug.Log (jdItems [i] ["path"]);
			//Debug.Log (jdItems [i] ["title"]);
			//Debug.Log (jdItems [i] ["author"]);

			string path=jdItems [i] ["path"].ToString();
			string title = jdItems [i] ["title"].ToString ();
			string author = jdItems [i] ["author"].ToString ();

			BookShelf bs = new BookShelf (path, title, author,"ShelfCell","ShelfGrid");

			GameObject cellPrefab = Resources.Load<GameObject> (bs.cellPath);
			GameObject cell = Instantiate (cellPrefab) as GameObject;

			StartCoroutine (LoadTheCover(bs,cell));

		}
	}
		

	/// <summary>
	/// 加载封面
	/// </summary>
	IEnumerator LoadTheCover(BookShelf bs,GameObject cell)
	{
		WWW www = new WWW (bs.theCoverPath);
		yield return www;
		if(string.IsNullOrEmpty(www.error))
		{
			bs.ResourcesCell (cell,www.texture);
		}
		else
		{
			Debug.LogError (www.error);
		}
	}

	public void Move(string way)
	{
		move.SetTrigger (way);
	}

}
